package com.haifeng.wdsh.business.sys.controller;

import com.alibaba.fastjson.JSON;
import com.haifeng.wdsh.common.base.exception.BusinessException;
import com.haifeng.wdsh.common.datasource.entity.User;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  基础Controller
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-05-06
 */
public class BaseController {

    public HttpServletRequest getServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes;
        if (requestAttributes instanceof ServletRequestAttributes) {
            servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    public User getUser() throws RuntimeException{
        String user = getServletRequest().getHeader("X-User");
        if (StringUtils.isEmpty(user)){
            throw new BusinessException(HttpStatus.FORBIDDEN.value(),"拒绝访问：未获取到用户信息");
        }
        return JSON.parseObject(getServletRequest().getHeader("X-User"),User.class);
    }
}
